package com.service.admin.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.service.admin.base.service.ConfigService;
import com.service.admin.order.controller.rep.OrderProductRep;
import com.service.admin.order.service.OrderProductOtherTotalService;
import com.service.core.exception.CommonException;
import com.service.core.rest.response.CommonPageRep;
import com.service.dao.constants.ConfigConstants;
import com.service.dao.model.SysConfig;
import com.service.dao.query.OrderParam;
import com.service.dao.enums.OrderProductOtherStatus;
import com.service.dao.mapper.OrderProductOtherMapper;
import com.service.dao.model.OrderProductOther;
import com.service.admin.order.controller.rep.OrderProductPageRep;
import com.service.admin.order.controller.req.OrderProductExpressReq;
import com.service.admin.order.controller.req.OrderProductPageReq;
import com.service.admin.order.service.OrderProductOtherDetailsService;
import com.service.admin.order.service.OrderProductOtherService;
import com.service.utility.modelmapper.ModelMapperUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <dl>
 * <dt>back-end</dt>
 * <dd>Description:</dd>
 * <dd>Copyright: Copyright (C) 2015</dd>
 * <dd>Company: </dd>
 * <dd>CreateDate: 2019年10月07日</dd>
 * </dl>
 *
 * @author
 */
@Slf4j
@Service
public class OrderProductOtherServiceImpl extends ServiceImpl<OrderProductOtherMapper, OrderProductOther> implements OrderProductOtherService {

    @Autowired
    private ConfigService configService;

    @Autowired
    private OrderProductOtherDetailsService orderProductOtherDetailsService;

    @Autowired
    private OrderProductOtherTotalService orderProductOtherTotalService;

    @Override
    public CommonPageRep<OrderProductPageRep> pageOrder(OrderProductPageReq pageReq) {
        Map<String, SysConfig> configMap = configService.getConfigMapByGroup(ConfigConstants.Group.mall.getCode());

        Page<OrderProductOther> page = PageHelper.startPage(pageReq.getPageNo(), pageReq.getPageSize());
        OrderParam orderParam = ModelMapperUtil.getStrictModelMapper().map(pageReq, OrderParam.class);
        baseMapper.listOrderByMemberAccount(orderParam);
        List<OrderProductPageRep> resultList = page.getResult().stream().map(item -> {
            OrderProductPageRep detail = ModelMapperUtil.getStrictModelMapper().map(item, OrderProductPageRep.class);
            detail.setDetailsList(orderProductOtherDetailsService.getOrderProductDetailsByOrderId(item.getId()));
            buildOrderDetailTotal(item, detail, configMap);
            return detail;
        }).collect(Collectors.toList());
        return CommonPageRep.buildResultRep(page, resultList);
    }

    private void buildOrderDetailTotal(OrderProductOther orderProductOther, OrderProductPageRep orderProductRep, Map<String, SysConfig> configMap) {
        Map<String, BigDecimal> totalMap = orderProductOtherTotalService.listTotalByOrderId2Map(orderProductOther.getId());

        Map<String, BigDecimal> payMoney = totalMap.entrySet().stream()
                .filter(map -> !(checkGiftCoin(map.getKey(), configMap)))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        Map<String, BigDecimal> giftNumMap = totalMap.entrySet().stream()
                .filter(map -> checkGiftCoin(map.getKey(), configMap))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        orderProductRep.setTotalMoney(payMoney);
        orderProductRep.setGiftMap(giftNumMap);
    }

    private boolean checkGiftCoin(String key, Map<String, SysConfig> configMap) {
        return StringUtils.equals(key, configMap.get(ConfigConstants.GIFT_ORDER_GIFT_COINS).getConfOptions())
                || StringUtils.equals(key, configMap.get(ConfigConstants.POINTS_ORDER_GIFT_COINS).getConfOptions());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deliverGoods(OrderProductExpressReq productExpressReq) {
        OrderProductOther product = baseMapper.selectById(productExpressReq.getId());
        if (ObjectUtils.isEmpty(product)) {
            throw new CommonException("订单不存在");
        }
        if(!ObjectUtils.nullSafeEquals(product.getOrderStatus(), OrderProductOtherStatus.PAYED.getCode())){
            throw new CommonException("订单状态错误");
        }
        baseMapper.updateById(OrderProductOther.builder()
                .id(product.getId())
                .orderStatus(OrderProductOtherStatus.DELIVERED.getCode())
                .expressName(productExpressReq.getExpressName())
                .expressNo(productExpressReq.getExpressNo())
                .build());
    }

    @Override
    public OrderProductPageRep getOrderDetail(Integer orderId) {
        OrderProductOther orderProductOther = baseMapper.selectById(orderId);
        if (ObjectUtils.isEmpty(orderProductOther)) {
            throw new CommonException("订单不存在");
        }
        OrderProductPageRep orderProductRep = ModelMapperUtil.getStrictModelMapper().map(orderProductOther, OrderProductPageRep.class);
        orderProductRep.setDetailsList(orderProductOtherDetailsService.getOrderProductDetailsByOrderId(orderId));
        return orderProductRep;
    }
}
